<script setup>
import { onMounted, ref, watch } from 'vue'
import { useTableList } from '@/hooks/useTableList'
import { useDict } from '@/hooks/useDict'
import { parkPageList } from '@/api/manager/dataManage/park'
import { getCheckProjectList } from '@/api/manager/inspectionManage/checkItemManage.js'
import {
  addCheckTable,
  getCheckTableDetail,
  updateCheckTable,
} from '@/api/manager/inspectionManage/checkTableManage.js'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
const router = useRouter()
const route = useRoute()

const { dict } = useDict([
  'inspection_check_project_type',
  'inspection_inspection_type',
  'inspection_inspection_scene',
  'yn',
])

const searchParams = ref({ typeId: '', senceId: '', itemTypeIds: '' })
const {
  Search,
  tableData,
  paginationParams,
  total,
  addRef,
  currentDetail,
  initTableList,
  handleSizeChange,
  handleReset,
  handleDelete,
  handleAdd,
  handleEdit,
  searchFromRef,
} = useTableList(searchParams, getCheckProjectList)

const parkOptions = ref([])
const initParkOptions = async () => {
  const res = await parkPageList({ pageIndex: 1, pageSize: 9999 })
  parkOptions.value = res.data.list
}

const tableRef = ref()
const multipleSelection = ref([])
const handleChangeSearchParams = async () => {
  searchParams.value = {
    typeId: form.value.typeId,
    senceId: form.value.senceId,
    itemTypeIds:
      form.value.itemTypeIds.length > 0
        ? form.value.itemTypeIds.join(',')
        : undefined,
  }
  multipleSelection.value = []
  await initTableList(1)
}

const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
const handleClose = () => {
  router.push({ name: 'checkTableManage' })
}
const loading = ref(false)
const formRef = ref()
const form = ref({ enabled: '1', status: '0' })
const rules = ref({
  areaIds: [{ required: true, message: '请选择适用园区', trigger: 'blur' }],
  typeId: [{ required: true, message: '请选择检查类型', trigger: 'blur' }],
  senceId: [{ required: true, message: '请选择检查场景', trigger: 'blur' }],
  name: [{ required: true, message: '请输入检查表名称', trigger: 'blur' }],
  itemTypeIds: [
    { required: true, message: '请选择检查项目类型', trigger: 'blur' },
  ],
})
const handleSubmit = async (isPublish) => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      if (isPublish && multipleSelection.value.length === 0) {
        ElMessage.warning('发布检查表时至少勾选一个自定义检查项')
        return
      }
      const itemIdArr = multipleSelection.value.map((i) => {
        return i.pkid
      })
      const params = {
        ...form.value,
        itemIds: itemIdArr || [],
        status: isPublish ? '1' : '0',
      }
      console.log('params', params)
      let res
      if (form.value.pkid) {
        res = await updateCheckTable(params)
      } else {
        res = await addCheckTable(params)
      }
      if (res.success) {
        ElMessage.success('保存成功')
        handleClose()
      } else {
        ElMessage.warning(res.message)
      }
    } else {
      ElMessage.warning('请正确录入信息')
    }
  })
}
const handleDetail = async () => {
  const res = await getCheckTableDetail({ pkid: route.query.pkid })
  if (res.success) {
    form.value = res.data
    await handleChangeSearchParams()
    handleToggleMultipleSelection(res.data.itemIds)
  } else {
    ElMessage.error(res.message)
  }
}
const handleToggleMultipleSelection = (ids) => {
  tableData.value.forEach((item) => {
    if (ids.includes(item.pkid)) {
      tableRef.value.toggleRowSelection(item, true)
    }
  })
}

const handleChangeName = () => {
  if (form.value.typeId && form.value.senceId) {
    getName()
  }
  handleChangeSearchParams()
}
const getName = () => {
  const senceObj = dict.value['inspection_inspection_scene'].find(
    (i) => i.value === form.value.senceId,
  )
  const typeObj = dict.value['inspection_inspection_type'].find(
    (i) => i.value === form.value.typeId,
  )
  form.value.name = `${typeObj.name}（${senceObj.name}）`
}
onMounted(() => {
  paginationParams.value.pageSize = 9999
  initParkOptions()
  if (route.query.pkid) {
    handleDetail()
  }
})
</script>

<template>
  <div class="check-table-manage-form">
    <div class="body">
      <div class="left">
        <div class="title">检查表信息</div>
        <div class="form">
          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="140"
            label-position="top"
          >
            <el-form-item label="适用园区" prop="areaIds">
              <el-select v-model="form.areaIds" placeholder="请选择" multiple>
                <el-option
                  v-for="item in parkOptions"
                  :key="item.pkid"
                  :label="item.name"
                  :value="item.pkid"
                  :disabled="item.enable === '0'"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="检查项目类型" prop="itemTypeIds">
              <el-select
                v-model="form.itemTypeIds"
                placeholder="请选择"
                multiple
                @change="handleChangeSearchParams"
              >
                <el-option
                  v-for="item in dict['inspection_check_project_type']"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="检查类型" prop="typeId">
              <el-select
                v-model="form.typeId"
                placeholder="请选择"
                @change="handleChangeName"
              >
                <el-option
                  v-for="item in dict['inspection_inspection_type']"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                  :disabled="item.value === '4'"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="检查场景" prop="senceId">
              <el-select
                v-model="form.senceId"
                placeholder="请选择"
                @change="handleChangeName"
              >
                <el-option
                  v-for="item in dict['inspection_inspection_scene']"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="检查表名称" prop="name">
              <el-input
                v-model="form.name"
                placeholder="检查类型（检查场景）"
                clearable
                :disabled="!form.typeId || !form.senceId"
              />
            </el-form-item>
            <el-form-item label="目的">
              <el-input
                type="textarea"
                v-model="form.purpose"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
            <el-form-item label="要求">
              <el-input
                type="textarea"
                v-model="form.require"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
            <el-form-item label="是否启用">
              <el-radio-group v-model="form.enabled">
                <el-radio
                  v-for="(item, index) of dict['yn']"
                  :key="index"
                  :value="item.value"
                  >{{ item.name }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="right">
        <div class="title">
          自定义检查项（注勾选项为默认配置，请根据实际情况需要勾选）
        </div>
        <el-table
          ref="tableRef"
          class="custom-table"
          :data="tableData"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="60px" />
          <el-table-column
            align="center"
            prop="itemTypeName"
            label="检查项目类型"
            width="150px"
          />
          <el-table-column align="center" prop="content" label="检查内容描述" />
        </el-table>
      </div>
    </div>
    <div class="footer">
      <el-button @click="handleClose" :loading="loading">取消</el-button>
      <el-button
        type="primary"
        v-if="!route.query.pkid || form.status === '0'"
        @click="handleSubmit(false)"
        :loading="loading"
        >保存</el-button
      >
      <el-button type="primary" @click="handleSubmit(true)" :loading="loading"
        >发布</el-button
      >
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import '@/assets/styles/table.scss';

.check-table-manage-form {
  position: relative;

  width: 100%;
  height: 100%;
  background: #fff;
  border-radius: 4px;

  .body {
    position: relative;
    display: flex;
    justify-content: space-between;
    height: calc(100% - 70px);
    border-bottom: 1px solid #f0f0f0;
  }

  .left {
    position: relative;
    height: 100%;
    width: 300px;
    box-sizing: border-box;
    border-right: 1px solid #f0f0f0;

    .title {
      padding: 12px 0;
      text-align: center;
      font-size: 16px;
      font-weight: 600;
      color: #333;
      border-bottom: 1px solid #f0f0f0;
    }

    .form {
      width: 100%;
      height: calc(100% - 44px);
      box-sizing: border-box;
      padding: 0 20px;
      overflow-y: auto;
    }
  }

  .right {
    flex: 1;
    box-sizing: border-box;
    padding: 10px;

    .title {
      padding: 10px 0;
      font-size: 12px;
      color: #777;
    }

    .pagination {
      display: flex;
      justify-content: flex-end;
    }
  }

  .footer {
    position: relative;
    padding: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
.custom-table {
  height: calc(100% - 35px) !important;
}
</style>
